package cn.gson.financial.kernel.service.impl;

import cn.gson.financial.kernel.model.entity.User;
import cn.gson.financial.kernel.model.entity.UserRoundupsBean;
import cn.gson.financial.kernel.model.mapper.AllSelectMapper;
import cn.gson.financial.kernel.model.mapper.UserRoundupsMapper;
import cn.gson.financial.kernel.model.vo.AccountRoleVo;
import cn.gson.financial.kernel.model.vo.AuditVo;
import cn.gson.financial.kernel.model.vo.UserVo;
import cn.gson.financial.kernel.model.vo.VoucherIdVo;
import cn.gson.financial.kernel.service.AccountSetsService;
import cn.gson.financial.kernel.service.UserRoundupsService;
import cn.gson.financial.kernel.service.UserService;
import cn.gson.financial.kernel.utils.RedisCacheManager;
import cn.gson.financial.kernel.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;


@Service
public class UserRoundupsServiceImpl implements UserRoundupsService {
    @Resource
    private UserRoundupsMapper userRoundupsMapper;
    @Autowired
    private RedisCacheManager redisCacheManager;
    @Autowired
    private AllSelectMapper allSelectMapper;
    @Autowired
    private AccountSetsService accountSetsService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public List<String> selectRoundupByUserId(String userId) {
        return userRoundupsMapper.selectRoundupByUserId(userId);
    }

    @Override
    public int insertRoundupByUserId(UserRoundupsBean bean) {
            String textContent = bean.getRoundup();
            textContent = textContent.trim();
            while (textContent.startsWith("　")) {
                textContent = textContent.substring(1, textContent.length()).trim();
            }
            while (textContent.endsWith("　")) {
                textContent = textContent.substring(0, textContent.length() - 1).trim();
            }
            System.out.println("-"+textContent+"-");
            if (textContent.equals("")){
                return 0;
            }else {
                bean.setRoundup(textContent);
                bean.setRoundupTime(new SimpleDateFormat().format(new Date()));
                String num = userRoundupsMapper.selectAllByRoundup(bean.getRoundup(),bean.getId());
                if (num==null){
                    userRoundupsMapper.insertRoundupByUserId(bean);
                }else {
                    num = Integer.toString(Integer.parseInt(num)+1);
                    userRoundupsMapper.updateRoundupNum(num,bean.getId(),bean.getRoundup(),bean.getRoundupTime());
                }
                return 1;
            }

    }


    @Override
    public String bridingPhone(String phone, String userId, String code) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();
        if (code.equals(redisCacheManager.get(phone+"binding"))){
            userRoundupsMapper.bridingPhone(phone,userId,date);
            return "success";
        }else {
            return "false";
        }
    }

    @Override
    public String updateUserPhone(String phone, String userId, String code) {
        String id = userRoundupsMapper.selectUserIdByphone(phone);
        if (id ==null||id.equals("")){
            if (code.equals(redisCacheManager.get(phone+"binding"))){
                userRoundupsMapper.updateUserPhone(phone,userId);
                return "修改成功";
            }else {
                return "验证码错误";
            }
        }else {

            return "该手机号已经进行绑定！";
        }
    }

    @Override
    public String updateUserPhoneHx(Integer wxUserId, String openId, String phone, String code, HttpSession session) {
        System.out.println("code"+code);
        System.out.println(redisCacheManager.get(phone+"binding"));

        int x = 0;
        if(code.equals(redisCacheManager.get(phone+"binding"))) {
            LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery();
            qw.eq(User::getMobile, phone);
            User user = userService.getOne(qw);
            //如果 用户为空,则说明该手机号码没有被绑定过,将该手机号进行绑定
            //如果不为空,则说明该手机号 已经被绑定,继续判断该用户是否有 openid或者密码
            //如果没有openId或者密码,则说明是 另一个账号在 分配账套权限
            //将 该手机号的账套权限 移植到 该openid下
            Date date = new Date();
            if (user == null) {
               x = userRoundupsMapper.updateUserPhoneHx(phone, openId,date);
            }else {
                if(user.getOpenId().equals("")|| user.getOpenId()==null){
                    //将手机号的权限 移植到 微信用户下(修改账套权限表)
                 userService.updateAccessAccountSetsRoleToUser(user.getId(), wxUserId);
                    //将空手机号 用户删除
                  userService.removeById(user.getId());
                    //将手机号绑定到微信用户
                  x = userRoundupsMapper.updateUserPhoneHx(phone, openId,date);
                }
            }
            if(x >0){
               UserVo userVo = userService.selectUser(openId);
                redisUtil.setAttribute( userVo,session);

                return "绑定成功!";
            }
            return "绑定失败!";
        }
        return "验证码错误!";
    }

    @Override
    public int auditNew(AuditVo vo, Integer accountSetsId) {
        System.out.println(vo);
        int cancels = 0;
        List<Integer> checkoutVoucherId = userRoundupsMapper.selectCheckoutVoucherId(accountSetsId);
        for (int i = 0; i <vo.getVoucherId().size() ; i++) {
            for (int j = 0; j <checkoutVoucherId.size() ; j++) {
                if (vo.getVoucherId().get(i).equals(checkoutVoucherId.get(j))){
                    vo.getVoucherId().remove(i);
                    i--;
                }
            }
        }
        for (int i = 0; i <vo.getVoucherId().size() ; i++) {
            int falg = userRoundupsMapper.updateAudit(vo.getVoucherId().get(i),vo.getAuditMemberId(),vo.getAuditMemberName(),vo.getAuditDate());
            if (falg == 1){
                cancels++;
            }
        }
        return cancels;
    }

    @Override
    public int cancelAuditNew(VoucherIdVo vo,Integer accountSetsId) {
        int cancels = 0;
        List<Integer> checkoutVoucherId = userRoundupsMapper.selectCheckoutVoucherId(accountSetsId);
        for (int i = 0; i <vo.getVoucherId().size() ; i++) {
            for (int j = 0; j <checkoutVoucherId.size() ; j++) {
                if (vo.getVoucherId().get(i).equals(checkoutVoucherId.get(j))){
                    vo.getVoucherId().remove(i);
                    i--;
                    break;
                }
            }
        }
        for (int i = 0; i < vo.getVoucherId().size(); i++) {
            int falg = userRoundupsMapper.cancelAudit(vo.getVoucherId().get(i));
            if (falg == 1){
                cancels++;
            }
        }
        return cancels;
    }

    @Override
    public void deleteVoucher(VoucherIdVo vo){
        for (int i = 0; i < vo.getVoucherId().size(); i++) {
            userRoundupsMapper.deleteVoucher(vo.getVoucherId().get(i));
            userRoundupsMapper.deleteVoucherD(vo.getVoucherId().get(i));
        }
    }

    public Boolean judgingNum(String role ,Integer accountSetsId){
        Integer num = userRoundupsMapper.judgingNum(role,accountSetsId);

        if (role.equals("Manager")){
            if (num>=2){
                return false;
            }
        }else {
            if (num>=1){
                return false;
            }
        }
        return true;
    }

    @Override
    public String addUserRole(String phone,String role ,Integer accountSetsId,String code){
        Boolean bool = judgingNum(role,accountSetsId);
        if (bool == false){
            return "此账套角色人数已达上限";
        }
        if (code.equals(redisCacheManager.get(phone+"power"))){
        //判断用户是否存在
            User user1 = allSelectMapper.selectUserByPhone(phone);
            if (user1!=null){
                //增加权限
                String res = accountSetsService.addUser(accountSetsId,phone,role);
                return res;
            }else {
                //创建用户
                User user2 = new User();
                user2.setMobile(phone);
                user2.setRealName(phone);
                userService.save(user2);
                //赋予角色
                String res = accountSetsService.addUser(accountSetsId,phone,role);
                return res;
            }
        }else {
            return "验证码错误";
        }
    }

    @Override
    public AccountRoleVo selectAccountRole(Integer accountSetsId){
        AccountRoleVo accountRoleVo = new AccountRoleVo();
        accountRoleVo.setMangerNum(allSelectMapper.selectAccountRole(accountSetsId,"Manager"));
        accountRoleVo.setViewNum(allSelectMapper.selectAccountRole(accountSetsId,"View"));
        accountRoleVo.setMakingNum(allSelectMapper.selectAccountRole(accountSetsId,"Making"));
        return accountRoleVo;
    }

    public static void main(String[] args) {
        System.out.println(LocalDateTime.now());

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = new Date();

        System.out.println(simpleDateFormat.format(date));
    }
}
